<template>
  <div class="product-attributes-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-select v-model="searchParams.productId" style="width: 300px; margin-right: 15px;" placeholder="请选择商品" clearable @change="handleProductChange">
        <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
      </el-select>
      <el-input v-model="searchParams.attrName" style="width: 240px; margin-right: 15px;" placeholder="请输入属性名" />
      <el-input v-model="searchParams.attrValue" style="width: 240px; margin-right: 15px;" placeholder="请输入属性值" />
      <el-icon @click="getAttributeList()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建属性</el-button>
      <el-button type="primary" plain style="margin-left: 15px;" @click="goBack">返回商品管理</el-button>
    </div>

    <!-- 商品属性表格 -->
    <el-table :data="attributeList" style="width: 100%" stripe border="true">
      <el-table-column label="序号" width="80px" #default="scope" align="center">
        {{ scope.$index + 1 }}
      </el-table-column>
  
      <el-table-column label="商品名称" width="200" align="center">
        <template #default="scope">
          {{ getProductName(scope.row.productId) }}
        </template>
      </el-table-column>
      <el-table-column prop="attrName" label="属性名" width="200" align="center" />
      <el-table-column prop="attrValue" label="属性值" width="200" align="center" />
      <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
        <el-button type="primary" plain @click="showEditDialog(scope.row)">修改</el-button>
        <el-button type="danger" plain @click="deleteAttribute(scope.row.id)">删除</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination 
        v-model:current-page="pagination.pageNum" 
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="pagination.total"
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
      />
    </div>

    <!-- 创建/编辑属性对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑商品属性' : '创建商品属性'" width="600px"
      :before-close="handleDialogClose" :close-on-click-modal="false">
      <el-form :model="attributeForm" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="attributeFormRef">
        <el-form-item label="商品" prop="productId">
          <el-select v-model="attributeForm.productId" placeholder="请选择商品" clearable>
            <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="属性名" prop="attrName">
          <el-input v-model="attributeForm.attrName" placeholder="请输入属性名" />
        </el-form-item>
        <el-form-item label="属性值" prop="attrValue">
          <el-input v-model="attributeForm.attrValue" placeholder="请输入属性值" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { productAttributeApi, productApi } from '@/api/product/product'
import { useRouter } from 'vue-router'

// 获取路由实例
const router = useRouter()

// 响应式数据
const attributeList = ref([])
const productList = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const attributeFormRef = ref()

// 搜索参数
const searchParams = reactive({
  productId: null,
  attrName: '',
  attrValue: ''
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 属性表单
const attributeForm = reactive({
  id: null,
  productId: null,
  attrName: '',
  attrValue: ''
})

// 表单验证规则
const formRules = {
  productId: [
    { required: true, message: '请选择商品', trigger: 'change' }
  ],
  attrName: [
    { required: true, message: '请输入属性名', trigger: 'blur' }
  ],
  attrValue: [
    { required: true, message: '请输入属性值', trigger: 'blur' }
  ]
}

// 获取属性列表
const getAttributeList = async () => {
  try {
    const params = {
      current: pagination.pageNum,
      size: pagination.pageSize,
      ...searchParams
    }
    
    const response = await productAttributeApi.list(params)
    
    if (response && response.records) {
      attributeList.value = response.records
      pagination.total = response.total
    } else {
      attributeList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取属性列表失败:', error)
    ElMessage.error('获取属性列表失败')
  }
}

// 获取商品列表
const getProductList = async () => {
  try {
    const response = await productApi.list({ current: 1, size: 1000 })
    if (response && response.records) {
      productList.value = response.records
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 获取商品名称
const getProductName = (productId) => {
  const product = productList.value.find(p => p.id === productId)
  return product ? product.name : ''
}

// 商品选择变化时自动刷新
const handleProductChange = () => {
  pagination.pageNum = 1
  getAttributeList()
}

// 重置搜索参数
const resetSearchParams = () => {
  Object.assign(searchParams, {
    productId: null,
    attrName: '',
    attrValue: ''
  })
  pagination.pageNum = 1
  getAttributeList()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  Object.assign(attributeForm, {
    id: null,
    productId: null,
    attrName: '',
    attrValue: ''
  })
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(attributeForm, {
    id: row.id,
    productId: row.productId,
    attrName: row.attrName,
    attrValue: row.attrValue
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await attributeFormRef.value.validate()
    
    const api = isEdit.value ? productAttributeApi.update : productAttributeApi.add
    const response = await api(attributeForm)
    
    if (response && response.success) {
      ElMessage.success(isEdit.value ? '属性更新成功' : '属性创建成功')
      dialogVisible.value = false
      getAttributeList()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除属性
const deleteAttribute = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该属性吗？', '提示', {
      type: 'warning'
    })
    
    const response = await productAttributeApi.delete(id)
    
    if (response && response.success) {
      ElMessage.success('删除成功')
      getAttributeList()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除属性失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  attributeFormRef.value?.resetFields()
  dialogVisible.value = false
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getAttributeList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.pageNum = current
  getAttributeList()
}

// 返回商品管理页面
const goBack = () => {
  router.push('/product_info')
}

// 初始化
onMounted(() => {
  getProductList()
  // 页面加载时获取所有属性，不限制商品
  getAttributeList()
})
</script>

<style scoped>
.product-attributes-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-icon {
  cursor: pointer;
  color: #409eff;
}

.search-bar .el-icon:hover {
  color: #66b1ff;
}
</style>
